﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.YCGLRD_TransManage.Com;
using ZK.Common;
using ZK.HardWareHelp;
using System.Threading;
using System.Diagnostics;

namespace ZK.YCGLRD_TransManage.UC
{
    public partial class WagonBalance : UserControl
    {

        private string NowCarNum = "";//当前车牌
        private string CameraIp = "";//已识别到车牌的车牌识别一体机的ip
        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();
        private string NowCardNum = "";//当前卡号
        public HardWareHelp.Camera cameraQ;
        public HardWareHelp.Camera cameraH;
        public HardWareHelp.Camera cameraG1;
        public HardWareHelp.Camera cameraG2;
        public HardWareHelp.Camera cameraK1;
        /// <summary>
        /// 当前重量
        /// </summary>
        public double nowWeight = 0;
        /// <summary>
        /// 过磅程序是否自动
        /// </summary>
        private bool isManual;
        static readonly object obj = new object();

        HardWareHelp.MW_102N_CardReader mW_102N_CardReader;

        HardWareHelp.TrafficLight trafficLightQ;
        HardWareHelp.TrafficLight trafficLightH;
        HardWareHelp.LingShengAudio lingShengAudio;
        HardWareHelp.NBKLD39WagonBalance NBKLD39WagonBalance;
        HardWareHelp.InfraredGrating infraredGrating;
        /// <summary>
        /// 地磅重量标准
        /// </summary>
        private double weightBZ;
        /// <summary>
        /// 地磅是否有数据
        /// </summary>
        private bool weightHaveDate;
        /// <summary>
        /// 红外数据
        /// </summary>
        private int InfraredGratingDate;
        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.YxYsTransportReturnDto yxYsTransportReturnDto;
        /// <summary>
        /// 红外遮挡时间间隔
        /// </summary>
        private int InfraredGratingTime;

        /// <summary>
        /// 摄像头已经识别的车牌列表
        /// </summary>
        private Dictionary<string, string> CarNumList = new Dictionary<string, string>();

        /// <summary>
        /// outdoor reaser repaet timer
        /// </summary>
        System.Timers.Timer outDoorReaderRepeatTimer = new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("OutDoorReaderRepeatTime")));
        /// <summary>
        /// car camera carnum repeat timer
        /// </summary>
        System.Timers.Timer carNumRepeatTimer = new System.Timers.Timer(Convert.ToInt32(AppConfigHelper.GetAppSettings("CarNumRepeatTime")));
        //List<double> weightList;
        //int weightCount;

        /// <summary>
        /// 构造函数
        /// </summary>
        public WagonBalance()
        {
            InitializeComponent();
            InitIsManual();
            //weightList = new List<double>();
            //weightCount = Convert.ToInt32(AppConfigHelper.GetAppSettings("weightListCount"));

            Common.DelegateHelper.CameraGetCarNumEvent += CameraGetCarNum;//车牌识别一体机识别到车牌的委托
            Common.DelegateHelper.MW_102N_MessageReceivedEvent += MW_102N_MessageReceived;//读卡器读到卡的委托
            Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;
            Common.DelegateHelper.WeightCallbackEvent += WeightCallback;
            DelegateHelper.InfraredGratingEvent += InfraredGratingEvent1;//红外光栅委托
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
            weightBZ = Convert.ToDouble(AppConfigHelper.GetAppSettings("weightBZ"));
            weightHaveDate = false;
            InfraredGratingTime = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfraredGratingTime"));

            InitCamera();
            InitReader();
            IniTrafficLight();
            InitLingSheng();
            InitWagonBalance();
            InitLed();
            InitInfraredGrating();

            if (isManual)
            {
                ButtonDKSPQ_Click(null, null);
                ButtonDKSPZ_Click(null, null);
                // this.Invoke(new Action(() => {
                button3.Visible = false;
                buttonDKSPQ.Visible = false;
                buttonDKSPZ.Visible = false;
                button4.Visible = false;
                button1.Visible = false;
                // }));
            }

            outDoorReaderRepeatTimer.Elapsed += OutDoorReaderRepeatTimer_Elapsed;
            outDoorReaderRepeatTimer.Enabled = true;
            outDoorReaderRepeatTimer.AutoReset = false;
            outDoorReaderRepeatTimer.Start();

            carNumRepeatTimer.Elapsed += CarNumRepeatTimer_Elapsed;
            carNumRepeatTimer.Enabled = true;
            carNumRepeatTimer.AutoReset = false;
            carNumRepeatTimer.Start();

            CarWithCarTimer.Elapsed += CarWithCarTimer_Elapsed;
            CarWithCarTimer.Enabled = true;
            CarWithCarTimer.AutoReset = false;
            CarWithCarTimer.Start();

        }

        private void CarWithCarTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Common.Log4.LogManage.WriteInfo("CarWithCarTimer_Elapsed 在车牌识别到规定时间内会判断是否上磅，如果没有，会清空车牌。");
            if (nowWeight < weightBZ && !string.IsNullOrEmpty(textBoxCarNum.Text.Trim()))
            {
                Common.Log4.LogManage.WriteInfo("CarWithCarTimer_Elapsed can not use wagonbalance carnum:" + textBoxCarNum.Text.Trim());
                ClearText();
            }
        }

        private void CarNumRepeatTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // throw new NotImplementedException();
        }

        private void OutDoorReaderRepeatTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        /// <summary>
        /// 初始化地磅的自动手动
        /// </summary>
        private void InitIsManual()
        {
            var resM = Com.WebApiService.ListWeighbridge(new Models.ListWeighbridgeSendM()
            {
                currentPage = 1,
                pageSize = 1,
                weighbridgeCode = Common.AppConfigHelper.GetAppSettings("WeighbridgeCode")
            });
            var wbM = resM.data[0];
            if (wbM.weighbridgeValue == Models.ListWeighbridgeReceiveM.weighbridgeValueEnum.自动过磅)
            {
                isManual = true;
            }
            if (wbM.weighbridgeValue == Models.ListWeighbridgeReceiveM.weighbridgeValueEnum.手动过磅)
            {
                isManual = false;
            }
        }

        /// <summary>
        /// 初始化红外光栅
        /// </summary>
        private void InitInfraredGrating()
        {
            infraredGrating = new InfraredGrating();
            infraredGrating.Open();
        }

        /// <summary>
        /// 红外光栅委托
        /// </summary>
        /// <param name="data"></param>
        private void InfraredGratingEvent1(int data)
        {
            //
            InfraredGratingDate = data;
        }

        /// <summary>
        /// 红外是否有遮挡的判断
        /// </summary>
        public void InfraredGratingJudge()
        {
            if (InfraredGratingDate != 3)
            {
                Thread.Sleep(InfraredGratingTime);
                LedPageShow(Com.TipsStringHelper.hwgsyzl);
                InfraredGratingJudge();
            }
        }

        /// <summary>
        /// 初始化led
        /// </summary>
        private void InitLed()
        {
            int a = OnbonBx_sdk_dual.InitSdk();
            ShowLed(TipsStringHelper.gldchyn);
        }

        /// <summary>
        /// 窗口自适应
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="height"></param>
        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }

        /// <summary>
        /// set weight in page
        /// </summary>
        public void SetWeightDataInPage()
        {
            try
            {
                this.Invoke(new Action(() =>
                   {
                       label4.Text = nowWeight.ToString();
                   }));
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteWarn("将地磅重量赋值给页面错误 " + ex.ToString());
            }
        }

        /// <summary>
        /// 地磅数据回调委托
        /// </summary>
        /// <param name="weight"></param>
        private void WeightCallback(double weight)
        {

            if (weight >= 0)
            {
                nowWeight = weight;
                SetWeightDataInPage();
                if (weight > weightBZ && !weightHaveDate)
                {
                    weightHaveDate = true;
                }
                //地磅上有数据 车完全下磅
                if (weight < weightBZ && weightHaveDate)
                {
                    ClearText();
                    weightHaveDate = false;

                }
            }

        }
        /// <summary>
        /// 清除页面数据
        /// </summary>
        private void ClearText()
        {
            Common.Log4.LogManage.WriteInfo("清空页面");
            try
            {
                this.Invoke(new Action(() =>
                    {
                        textBoxCardNum.Text = "";
                        textBoxCarNum.Text = "";
                        textBoxKZT.Text = "";
                        textBoxLX.Text = "";
                        textBoxHWMC.Text = "";
                        textBoxCYS.Text = "";
                        textBoxGSM.Text = "";
                        textBoxBZ.Text = "";
                        textBoxCZZL.Text = "";
                    }));
                yxYsTransportReturnDto = null;
                CarNumSetIfListHave();
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteWarn("清空数据出错 " + ex.ToString());
            }
        }

        /// <summary>
        /// 设置页面数据
        /// </summary>
        private void SetText()
        {
            try
            {
                this.Invoke(new Action(() =>
                   {
                       textBoxKZT.Text = Enum.GetName(typeof(SysDefinitionEnum.SendType), yxYsTransportReturnDto.sendType);
                       textBoxCYS.Text = yxYsTransportReturnDto.carrierName;
                       textBoxGSM.Text = yxYsTransportReturnDto.shipperName;
                       textBoxHWMC.Text = yxYsTransportReturnDto.cargoName;
                       textBoxBZ.Text = yxYsTransportReturnDto.memo;
                       textBoxLX.Text = Enum.GetName(typeof(SysDefinitionEnum.TruckState), yxYsTransportReturnDto.truckState);
                   }));
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteWarn("设置页面数据出错 " + ex.ToString());
            }
        }

        /// <summary>
        /// 初始化地磅
        /// </summary>
        private void InitWagonBalance()
        {
            NBKLD39WagonBalance = new HardWareHelp.NBKLD39WagonBalance();
        }

        /// <summary>
        /// 初始化菱声网络音响   
        /// </summary>
        private void InitLingSheng()
        {
            lingShengAudio = new HardWareHelp.LingShengAudio();
           
        }

        /// <summary>
        /// 初始化红绿灯
        /// </summary>
        private void IniTrafficLight()
        {
            trafficLightQ = new HardWareHelp.TrafficLight(Common.IConfig.GetSetTrafficLightQ);
            trafficLightH = new HardWareHelp.TrafficLight(Common.IConfig.GetSetTrafficLightH);
            trafficLightQ.GreenLight();
            trafficLightH.GreenLight();
        }

        /// <summary>
        /// 初始化室外读卡器
        /// </summary>
        private void InitReader()
        {
            // mW_102N_CardReader = new HardWareHelp.MW_102N_CardReader("192.168.12.61", 6000);
            mW_102N_CardReader = new HardWareHelp.MW_102N_CardReader();
        }

        /// <summary>
        /// 初始化摄像头
        /// </summary>
        private void InitCamera()
        {
            Task.Factory.StartNew(() =>
            {
                //Q
                {
                    Common.HaredWareCommonM cameraScalesQ = Common.IConfig.GetSetCameraScalesQ;
                    Common.CameraModel cameraModelQ = new Common.CameraModel()
                    {
                        Name = cameraScalesQ.Name,
                        Ip = cameraScalesQ.Ip,
                        Port = Convert.ToInt32(cameraScalesQ.Port),
                        PassWord = cameraScalesQ.PassWord,
                        UserName = cameraScalesQ.UserName
                    };
                    cameraQ = new HardWareHelp.Camera(cameraModelQ);
                }
                //H
                {
                    Common.HaredWareCommonM cameraScalesH = Common.IConfig.GetSetCameraScalesH;
                    Common.CameraModel cameraModelH = new Common.CameraModel()
                    {
                        Name = cameraScalesH.Name,
                        Ip = cameraScalesH.Ip,
                        Port = Convert.ToInt32(cameraScalesH.Port),
                        PassWord = cameraScalesH.PassWord,
                        UserName = cameraScalesH.UserName
                    };
                    cameraH = new HardWareHelp.Camera(cameraModelH);
                }
                //G1
                {
                    Common.HaredWareCommonM cameraScalesG1 = Common.IConfig.GetSetCameraScalesG1;
                    Common.CameraModel cameraModelG1 = new Common.CameraModel()
                    {
                        Ip = cameraScalesG1.Ip,
                        Name = cameraScalesG1.Name,
                        Port = Convert.ToInt32(cameraScalesG1.Port),
                        PassWord = cameraScalesG1.PassWord,
                        UserName = cameraScalesG1.UserName
                    };
                    cameraG1 = new HardWareHelp.Camera(cameraModelG1);
                }
                //G2
                {
                    Common.HaredWareCommonM cameraScalesG2 = Common.IConfig.GetSetCameraScalesG2;
                    Common.CameraModel cameraModelG2 = new Common.CameraModel()
                    {
                        Ip = cameraScalesG2.Ip,
                        Name = cameraScalesG2.Name,
                        Port = Convert.ToInt32(cameraScalesG2.Port),
                        PassWord = cameraScalesG2.PassWord,
                        UserName = cameraScalesG2.UserName
                    };
                    cameraG2 = new HardWareHelp.Camera(cameraModelG2);
                }
                //K1
                {
                    Common.HaredWareCommonM cameraScalesK1 = Common.IConfig.GetSetCameraScalesK1;
                    Common.CameraModel cameraModelK1 = new Common.CameraModel()
                    {
                        Ip = cameraScalesK1.Ip,
                        Name = cameraScalesK1.Name,
                        Port = Convert.ToInt32(cameraScalesK1.Port),
                        PassWord = cameraScalesK1.PassWord,
                        UserName = cameraScalesK1.UserName
                    };
                    cameraK1 = new HardWareHelp.Camera(cameraModelK1);
                }


            });
        }

        /// <summary>
        /// 登录抓拍摄像头
        /// </summary>
        private void InitZPCamera()
        {

            cameraG1.ManualOne(pictureBoxG1);
            cameraG2.ManualOne(pictureBoxG2);
            cameraK1.ManualOne(pictureBoxK1);
        }

        //private void SendWidthHeight(int Width, int height)
        //{
        //    if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
        //    {
        //        wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
        //        wFAutoSizeHelper.ControlsChange(this.Controls[0]);
        //    }
        //}


        /// <summary>
        /// 室外读卡器数据获取委托
        /// </summary>
        /// <param name="cardNum"></param>
        private void MW_102N_MessageReceived(string cardNum)
        {
            lock (obj)
            {
                Common.Log4.LogManage.WriteInfo("程序拿到卡号：" + cardNum);
                if (NowCardNum == cardNum)
                {
                    if (outDoorReaderRepeatTimer.Enabled)
                    {
                        Common.Log4.LogManage.WriteInfo("当卡号从 读卡器中传来的时候，软件中做的时间间隔限制还在运行，不允许操作卡号。");
                    }
                    else
                    {
                        DoSomthing();
                    }
                }
                else
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        textBoxCardNum.Text = cardNum;
                        NowCardNum = cardNum;
                    }));
                    DoSomthing();

                }
            }
        }
        /// <summary>
        /// car with car timer
        /// </summary>
        System.Timers.Timer CarWithCarTimer = new System.Timers.Timer(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("CarWithCar")));

        /// <summary>
        /// 获取到车牌的委托事件
        /// </summary>
        /// <param name="carNum"></param>
        /// <param name="cameraIp"></param>
        private void CameraGetCarNum(string carNum, string cameraIp)
        {
            Common.Log4.LogManage.WriteInfo("程序get车牌:" + carNum + " ip：" + cameraIp);
            if (!CarNumList.ContainsKey(carNum))
            {
                CarNumList.Add(carNum, cameraIp);
            }
            string tempCar = textBoxCarNum.Text.Trim();
            if (nowWeight < weightBZ && string.IsNullOrWhiteSpace(tempCar))
            {
                try
                {
                    //if (!CarWithCarTimer.Enabled)
                    //{
                    //    CarWithCarTimer.Start();
                    //}
                    CarWithCarTimer.Stop();
                    CarWithCarTimer.Start();

                    CarNumList.Remove(NowCarNum);

                    LedPageShow(TipsStringHelper.dqcp + carNum);
                    Common.Log4.LogManage.WriteInfo("页面车牌号赋值，车牌号：" + carNum);
                    this.Invoke(new Action(() =>
                    {
                        textBoxCarNum.Text = carNum;
                    }));
                    NowCarNum = carNum;
                    CameraIp = cameraIp;
                    Common.Log4.LogManage.WriteInfo("调用是否黑名单接口");
                    var resCarM = Com.WebApiService.GetBlack(carNum);
                    if (resCarM == null)
                    {
                        MessageThrow("GetBlack接口调用失败，请稍后重试！");
                    }
                    if (resCarM.data)
                    {
                        MessageThrow(TipsStringHelper.dqcp + carNum + TipsStringHelper.hmd);
                    }
                    else
                    {
                        Common.Log4.LogManage.WriteInfo("扫到车牌判断接口");
                        var resM = Com.WebApiService.JudgeTruckNo(carNum);
                        if (!resM.success)
                        {
                            MessageThrow(resM.msg);
                        }
                        Common.Log4.LogManage.WriteInfo("开启道闸");

                        if (CameraIp == cameraQ.cameraModel.Ip) cameraQ.BarrierGateControl(1);
                        if (CameraIp == cameraH.cameraModel.Ip) cameraH.BarrierGateControl(1);
                        Common.Log4.LogManage.WriteInfo("显示红灯");
                        trafficLightQ.RedLight();
                        trafficLightH.RedLight();
                    }
                }
                catch (Exception ex)
                {
                    LedPageShow(ex.Message);
                    Common.Log4.LogManage.WriteWarn(ex.ToString());
                }




            }
        }

        private void CameraGetCarNum1(string carNum, string cameraIp)
        {
            Common.Log4.LogManage.WriteInfo("称重页面拿到了车牌:" + carNum + " 摄像头ip：" + cameraIp);

            if (nowWeight < weightBZ)
            {
                try
                {
                    //if (!CarWithCarTimer.Enabled)
                    //{
                    //    CarWithCarTimer.Start();
                    //}
                    CarWithCarTimer.Stop();
                    CarWithCarTimer.Start();


                    this.Invoke(new Action(() =>
                    {
                        textBoxCarNum.Text = carNum;
                    }));
                    LedPageShow(TipsStringHelper.dqcp + carNum);
                    CarNumList.Remove(carNum);
                    NowCarNum = carNum;
                    CameraIp = cameraIp;
                    Common.Log4.LogManage.WriteInfo("是否黑名单接口");
                    var resCarM = Com.WebApiService.GetBlack(carNum);
                    if (resCarM.data)
                    {
                        MessageThrow(TipsStringHelper.dqcp + carNum + TipsStringHelper.hmd);
                    }
                    else
                    {
                        Common.Log4.LogManage.WriteInfo("扫到车牌判断接口");
                        var resM = Com.WebApiService.JudgeTruckNo(carNum);
                        if (!resM.success)
                        {
                            MessageThrow(resM.msg);
                        }
                        Common.Log4.LogManage.WriteInfo("开启道闸");
                        if (CameraIp == cameraQ.cameraModel.Ip) Common.Log4.LogManage.WriteInfo("road gate cameraQ.BarrierGateControl(1) " + cameraQ.BarrierGateControl(1));
                        if (CameraIp == cameraH.cameraModel.Ip) Common.Log4.LogManage.WriteInfo("road gate cameraH.BarrierGateControl(1) " + cameraH.BarrierGateControl(1));
                        Common.Log4.LogManage.WriteInfo("显示红灯");
                        trafficLightQ.RedLight();
                        trafficLightH.RedLight();
                    }
                }
                catch (Exception ex)
                {
                    LedPageShow(ex.Message);
                    Common.Log4.LogManage.WriteWarn(ex.ToString());
                }


            }
        }

        /// <summary>
        /// 两个led同时显示消息
        /// </summary>
        /// <param name="str"></param>
        private void ShowLed(string str)
        {
            //Task.Factory.StartNew(() =>
            //{
            try
            {
                HaredWareCommonM ledQ = IConfig.GetSetLedQ;
                Common.TestConnect.CheckDeviceStatus(ledQ.Ip, ledQ.Name);
                OnbonBx_sdk_dual.dynamicArea_6(str, ledQ.Ip);

                HaredWareCommonM ledH = IConfig.GetSetLedH;
                Common.TestConnect.CheckDeviceStatus(ledH.Ip, ledH.Name);
                OnbonBx_sdk_dual.dynamicArea_6(str, ledH.Ip);
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteWarn("led显示失败！ ex:" + ex.ToString());
            }
            // });
        }

        /// <summary>
        /// 车牌号、卡号赋值更新委托
        /// </summary>
        private void DoSomthing()
        {
            Common.Log4.LogManage.WriteInfo("拿到卡号，开始做事");
            if (!outDoorReaderRepeatTimer.Enabled)
            {
                outDoorReaderRepeatTimer.Start();

            }
            Common.Log4.LogManage.WriteInfo("判断卡号车牌号都不为空");
            if (!string.IsNullOrEmpty(textBoxCarNum.Text.Trim()) && !string.IsNullOrEmpty(textBoxCardNum.Text.Trim()))
            {
                Button3_Click(null, null);
            }
        }

        /// <summary>
        /// 车牌号更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxCarNum_TextChanged(object sender, EventArgs e)
        {
            Common.DelegateHelper.SetCarNumEvent?.Invoke();
        }

        /// <summary>
        /// 卡号更新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxCardNum_TextChanged(object sender, EventArgs e)
        {
            Common.DelegateHelper.SetCarNumEvent?.Invoke();
        }

        /// <summary>
        /// 打开前摄像头按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonDKSPQ_Click(object sender, EventArgs e)
        {
            cameraQ.ManualOne(pictureBoxQ);

            InitZPCamera();
        }

        /// <summary>
        /// 打开后摄像头按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonDKSPZ_Click(object sender, EventArgs e)
        {
            cameraH.ManualOne(pictureBoxH);
        }

        /// <summary>
        /// 窗口尺寸改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WagonBalance_SizeChanged(object sender, EventArgs e)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(this.Controls[0]);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
                Common.DelegateHelper.SendWidthHeightEvent?.Invoke(this.Controls[0].Width, this.Controls[0].Height);
            }
        }

        /// <summary>
        /// get carnum now
        /// </summary>
        /// <returns></returns>
        public string GetCarNumNow()
        {
            return textBoxCardNum.Text.Trim();
        }

        /// <summary>
        /// 车牌号卡号都存在时查询信息按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, EventArgs e)
        {
            Common.Log4.LogManage.WriteInfo("根据卡号车牌号查询相关信息");
            //Stopwatch stw = new Stopwatch();
            //stw.Start();
            //long s1 = stw.ElapsedMilliseconds;
            try
            {
                //long a1 = stw.ElapsedMilliseconds;
                //long a2 = stw.ElapsedMilliseconds;
                //Common.Log4.LogManage.WriteInfo("infraredGrating.Open time:" + (a2 - a1));
                string cardNum = GetCarNumNow();

                //查询运销信息并给页面赋值
                Common.Log4.LogManage.WriteInfo("查询运销信息，并显示");
                var YxRes = Com.WebApiService.GetTruckYxInfo(cardNum);

                if (YxRes.data != null)
                {
                    yxYsTransportReturnDto = YxRes.data;
                    SetText();
                }

                Common.Log4.LogManage.WriteInfo("判断过磅程序是否开启了自动");
                if (isManual)
                {
                    Button4_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                LedPageShow(TipsStringHelper.cxyc);
                Common.Log4.LogManage.WriteWarn(TipsStringHelper.dbcxan + " " + ex.ToString());
            }

            //long s2 = stw.ElapsedMilliseconds;
            //Common.Log4.LogManage.WriteInfo("Button3_Click 查询按钮消耗总时间：" + (s2 - s1));
            //stw.Stop();
        }

        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="str"></param>
        void MessageThrow(string str)
        {
            throw new Exception(str);
        }

        /// <summary>
        /// 称重按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, EventArgs e)
        {
            Common.Log4.LogManage.WriteInfo("开始自动过磅！");
            int? clcz = 0;
            try
            {
                Common.Log4.LogManage.WriteInfo("地磅重量是否达标");
                if (nowWeight < weightBZ)
                {
                    MessageThrow(TipsStringHelper.zlbdb);
                }


                List<string> picCodeList = new List<string>();
                string cardNum, carNum, imgs1;
                cardNum = GetCarNumNow();
                carNum = textBoxCarNum.Text.Trim();
                Common.Log4.LogManage.WriteInfo("当前车牌：" + carNum + " 卡号：" + cardNum + " 重量：" + nowWeight);
                double ww = nowWeight;
                textBoxCZZL.Text = nowWeight.ToString();
                Common.Log4.LogManage.WriteInfo("判断红外");
                InfraredGratingJudge();
                Common.Log4.LogManage.WriteInfo("判断采购销售类型");
                var resModel = Com.WebApiService.GetSendTypeByCardNo(cardNum);
                if (!resModel.success)
                {
                    MessageThrow(resModel.msg);
                }
                //获取三张监控的图片
                Common.Log4.LogManage.WriteInfo("高空摄像头拍照");
                string picG1 = cameraG1.UpLoadFile();
                if (!string.IsNullOrWhiteSpace(picG1))
                {
                    picCodeList.Add(picG1);
                }
                string picG2 = cameraG2.UpLoadFile();
                if (!string.IsNullOrWhiteSpace(picG2))
                {
                    picCodeList.Add(picG2);
                }
                string picK1 = cameraK1.UpLoadFile();
                if (!string.IsNullOrWhiteSpace(picK1))
                {
                    picCodeList.Add(picK1);
                }
                imgs1 = string.Join(",", picCodeList);
                //采购
                if (resModel.data == 1)
                {
                    if (yxYsTransportReturnDto == null)
                    {
                        Common.Log4.LogManage.WriteInfo("称重");
                        var cz = Com.WebApiService.TruckWeigh(
                                              new Models.WeightDtoSendM()
                                              {
                                                  cardNo = cardNum,
                                                  wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                  imgs2 = imgs1,
                                                  mz = ww,
                                                  truckNo = carNum
                                              }
                                              );
                        if (!cz.success)
                        {
                            MessageThrow(cz.msg);
                        }
                        LedPageShow(cz.msg);
                        clcz = cz.data;
                        Common.Log4.LogManage.WriteInfo("播放音频");
                        lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCZ")));
                    }
                    else
                    {

                        if ((yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.出场_收) || (yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.除皮_收))
                        {
                            Common.Log4.LogManage.WriteInfo("除皮");
                            var cp = Com.WebApiService.TruckTare(
                                                                 new Models.TareDtoSendM()
                                                                 {
                                                                     cardNo = cardNum,
                                                                     wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                                     imgs1 = imgs1,
                                                                     pz = ww,
                                                                     truckNo = carNum
                                                                 }
                                                                 );
                            if (!cp.success)
                            {
                                MessageThrow(cp.msg);
                            }
                            LedPageShow(cp.msg);
                            //--------------------------------------------
                            Common.Log4.LogManage.WriteInfo("播放音频");
                            lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCP")));
                        }
                        if (yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.称重_收)
                        {
                            Common.Log4.LogManage.WriteInfo("称重");
                            var cz = Com.WebApiService.TruckWeigh(
                                             new Models.WeightDtoSendM()
                                             {
                                                 cardNo = cardNum,
                                                 wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                 imgs2 = imgs1,
                                                 mz = ww,
                                                 truckNo = carNum
                                             }
                                             );
                            if (!cz.success)
                            {
                                MessageThrow(cz.msg);
                            }
                            LedPageShow(cz.msg);
                            clcz = cz.data;
                            Common.Log4.LogManage.WriteInfo("播放音频");
                            lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCZ")));

                        }
                    }

                }
                // 2销售
                else
                {
                    if (yxYsTransportReturnDto == null)
                    {
                        Common.Log4.LogManage.WriteInfo("除皮");
                        var cp = Com.WebApiService.TruckTare(
                                                 new Models.TareDtoSendM()
                                                 {
                                                     cardNo = cardNum,
                                                     wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                     imgs1 = imgs1,
                                                     pz = ww,
                                                     truckNo = carNum
                                                 }
                                             );
                        if (!cp.success)
                        {
                            MessageThrow(cp.msg);
                        }
                        LedPageShow(cp.msg);
                        Common.Log4.LogManage.WriteInfo("播放音频");
                        lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCP")));
                    }
                    else
                    {

                        if ((yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.出场_发) || (yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.称重_发))
                        {
                            Common.Log4.LogManage.WriteInfo("称重");
                            var cz = Com.WebApiService.TruckWeigh(
                                                                      new Models.WeightDtoSendM()
                                                                      {
                                                                          cardNo = cardNum,
                                                                          wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                                          imgs2 = imgs1,
                                                                          mz = ww,
                                                                          truckNo = carNum
                                                                      }
                                                                  );
                            if (!cz.success)
                            {
                                MessageThrow(cz.msg);
                            }
                            LedPageShow(cz.msg);
                            clcz = cz.data;
                            Common.Log4.LogManage.WriteInfo("播放音频");
                            lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCZ")));

                        }
                        if (yxYsTransportReturnDto.yxState == SysDefinitionEnum.YxState.除皮_发)
                        {
                            Common.Log4.LogManage.WriteInfo("除皮");
                            var cp = Com.WebApiService.TruckTare(
                                                new Models.TareDtoSendM()
                                                {
                                                    cardNo = cardNum,
                                                    wgbid = Convert.ToInt32(AppConfigHelper.GetAppSettings("WeighbridgeId")),
                                                    imgs1 = imgs1,
                                                    pz = ww,
                                                    truckNo = carNum
                                                }
                                            );
                            if (!cp.success)
                            {
                                MessageThrow(cp.msg);
                            }
                            LedPageShow(cp.msg);
                            Common.Log4.LogManage.WriteInfo("播放音频");
                            lingShengAudio.AutoStartTask(Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("LingShengCP")));

                        }
                    }
                }
                if (clcz == 10)
                {
                    MessageThrow("车辆超载，请联系管理员处理！");
                }
                //道闸开
                Common.Log4.LogManage.WriteInfo("道闸开");
                if (CameraIp == cameraQ.cameraModel.Ip) cameraH.BarrierGateControl(1);
                if (CameraIp == cameraH.cameraModel.Ip) cameraQ.BarrierGateControl(1);
                //ClearText();
            }
            catch (Exception ex)
            {
                LedPageShow(ex.Message);
                Common.Log4.LogManage.WriteWarn(TipsStringHelper.dbczansj + " " + ex.ToString());
            }

        }

        /// <summary>
        /// 判断后续是否还有车
        /// </summary>
        public void CarNumSetIfListHave()
        {
            CarNumList.Remove(NowCarNum);
            NowCardNum = "";
            NowCarNum = "";
            CameraIp = "";
            if (CarNumList.Count > 0)
            {
                var temp = CarNumList.First();
                CameraGetCarNum1(temp.Key, temp.Value);
            }
            else
            {
                LedPageShow(TipsStringHelper.gldchyn);
                trafficLightQ.GreenLight();
                trafficLightH.GreenLight();
            }
        }

        /// <summary>
        ///提示信息显示在led和页面上
        /// </summary>
        /// <param name="str"></param>
        private void LedPageShow(string str)
        {
            Common.Log4.LogManage.WriteInfo("在页面以及led上显示的内容：" + str);
            ShowLed(str);
            MessageShow(str);


        }

        /// <summary>
        /// led,页面，异常都显示
        /// </summary>
        /// <param name="str"></param>
        private void LedMessageThrow(string str)
        {
            ShowLed(str);
            MessageShow(str);
            MessageThrow(str);
        }

        /// <summary>
        /// 页面上显示信息
        /// </summary>
        /// <param name="str"></param>
        private void MessageShow(string str)
        {
            try
            {
                this.Invoke(new Action(() =>
                   {
                       labelInfoShow.Text = str;
                   }));
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteWarn("页面显示信息失败! " + ex.ToString());
            }
        }

        /// <summary>
        /// 清空按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click(object sender, EventArgs e)
        {
            ClearText();
        }
    }
}
